/**
 * this file put the public method.
 */


var tplBaseUrl = '',
    debug = true;
/**
 * [constant 全局静态变量]
 * @type {Object}
 */
var constant = {
    // BASE_URL: 'http://192.168.1.103:3366',
    //BASE_URL: 'http://192.168.0.5:3366',
    //BASE_URL: 'http://192.168.1.16:3366',
     //BASE_URL: 'http://101.200.228.228',
     //BASE_URL: 'http://101.200.228.228',
    IMG_URL: 'http://192.168.1.103:3366/upload/',
    INTERFACE_LOGIN: 'http://www.appcan.cn',
    PARAMS: {
        SUBJECT_KEY: 'subjectId', // 视野列表跳专题列表
        VISION_KEY: 'visionId', // 视野列表跳详情页面
    },
    VAR: {
        USER_KEY: 'userinfo', // 用户信息
    }
}


/**
 * [tools 工具]
 * @type {Object}
 */
var tools = {
    isPhone: (window.navigator.platform != "Win32"),
    stopswipe: function () {
        appcan.window.setWindowScrollbarVisible(0);
        appcan.window.disableBounce();
        tools.isPhone && uexWindow.setMultilPopoverFlippingEnbaled(1);
        // tools.isPhone && appcan && appcan.window && appcan.window.setMultilPopoverFlippingEnbaled && appcan.window.setMultilPopoverFlippingEnbaled(0);
    },
    winInfoKey: 'winInfo',
    initWinInfo: function (){
        var winWidth = $(window).width(),
            winHeight = $(window).height(),
            winInfoKey = this.winInfoKey,
            winInfo = LS.get(winInfoKey);
        LS.set(winInfoKey, {
            width: winWidth,
            height: winHeight
        });
    },
    getWinInfo: function () {
        var that = this;
        return LS.get(that.winInfoKey);
    },
    /**
     * [bindPublicToWindow 绑定_public到window上]
     * @return {[type]} [description]
     */
    bindPublicToWindow: function () {
        var _key;
        for(_key in _publics){
            window[_key] = _publics[_key];
        }
    },
    /**
     * [getImgPath 获取图片的路径]
     * @param  {[type]} url [description]
     * @return {[type]}     [description]
     */
    getImgPath: function (url) {
        return url ? constant.IMG_URL + url : '';
    }
}


/**
 * [_publics 公共函数，绑定在window上]
 * @type {Object}
 */
var _publics = {
    /**
     * [bindEvent 事件绑定]
     * @param  {[type]}   selector [description]
     * @param  {Function} callback [description]
     * @return {[type]}            [description]
     */
    bindEvent: function (selector, callback) {
        setTimeout(function () {
            appcan.button(selector, "btn-act", function() {

                callback && callback.call(this);

            })
        }, 10);
    },
    bindClose: function (selector) {

        appcan.button(selector, "btn-act", function() {
            appcan.window.close(-1);
        })

    },
    /**
     * [checkIndex check the index is not a number or not]
     * @param  {[type]} index [description]
     * @return {[type]}       [description]
     */
    checkIndex: function (index) {
        if(isNaN(index)) throw new TypeError('index('+index+') should be a number');
    },
    $H: function (dom) {
        return $(dom).height();
    },
    $W: function (dom) {
        return $(dom).width();
    },
    /**
     * [loadTemplate 加载本地模板]
     * @param  {[type]} tpl [description]
     * @return {[type]}     [description]
     */
    loadTemplate: function (tpl) {
        $.ajax({
            url : tplBaseUrl + tpl,
            type : 'GET',
            data : {}, //默认从参数获取
            timeout : 10000,
            async : false,
            success : function(data) {
                template = _.template(data);
            },
            error : function(e) {
            }
        });
        return template;
    },
    /**
     * [post post请求]
     * @param  {[type]} url             [description]
     * @param  {[type]} data            [description]
     * @param  {[type]} successCallback [description]
     * @param  {[type]} failureCallback [description]
     * @return {[type]}                 [description]
     */
    post: function () {
        if(arguments.length < 3) throw new Error('arguments number is not right');
        var url = arguments[0],
            data = arguments[1],
            successCallback = arguments[2],
            failureCallback = arguments[3];

        url = constant.BASE_URL + url;

        debug && console.log('url: ' + url);
        appcan.ajax({
            url : url,
            type : 'POST',
            dataType: 'json',
            data : data,
            success : function(data) {
                if(data.hasOwnProperty('code') && data.code){
                    return alert(data.result);
                }
                debug && console.log('response data: ');
                debug && console.log(data);
                successCallback && successCallback.call(null, data.result, data.counts);
            },
            error : function(e, err) {
                console && console.error(e);
                console && console.error(err);
                failureCallback && failureCallback.call(null, err);
            }
        });
    }
};

/**
 * window窗口操作相关
 * @type {Object}
 */
var Win = {
    /**
     * @param String name 新窗口名称
     * @param String aimID 打开动画
     */
    open: function(name, aimID) {
        appcan.window.open({
            name: name,
            dataType: 0,
            aniId: (aimID != undefined ? aimID : 10),
            data: name + ".html",
            extraInfo: {
                opaque: true,
                bgColor: 'rgb(0,0,0)'
            }
        });
    },
    /**
     * [openMain 打开主窗口]
     * @param  {[type]} name [description]
     * @return {[type]}      [description]
     */
    openMain: function (name, path) {
        uexWindow.open(name, '0', path+'.html', '0', '0', '0', '36', '200'); // 32+4(for why)
    },
    /**
     * [openPopver 打开浮动窗口]
     * @return {[type]} [description]
     */
    openPopover: function (name, top, left, width, height) {
        var popoverParam = {
            name: (~name.indexOf('.html') ? name.replace('.html', '') : name),
            dataType: 0,
            url: (~name.indexOf('.html') ? name : name + '.html')
        };
        if(top) popoverParam.top = top;
        if(left) popoverParam.left = left;
        if(width) popoverParam.width = width;
        if(height) popoverParam.height = height;

        appcan.window.openPopover(popoverParam)
    },
    toast: function (mes, time, showLoading) { // 消息提示
        appcan.window.openToast(mes, time || 1000, '5', showLoading ? 1 : 0);
    },
    closeToast: function(){ // 关闭消息提示
        appcan.window.closeToast();
    },
    msgOpenFlag: false, // 关闭标签
    msg: '', // 弹框显示的消息内容
    msgShow: function (mainWin, _msg) {
        var that = this,
            winInfo = tools.getWinInfo(),
            winWidth = winInfo.width,
            winHeight = winInfo.height,
            height = width = 4/15 * winWidth,
            left = (winWidth - width) / 2,
            top = (winHeight - height) / 2;
        if(!that.msgOpenFlag){
            Win.openPopover('msg', top, left, width, height);
            EventUtil.deferFire([500, function () {
                appcan.c.pop('msg', '$("#msg").text("'+_msg+'")', mainWin);
                that.msgOpenFlag = true;
            }], [1000, function () {
                that.msgHide();
            }]);
        }
    },
    msgHide: function () {
        appcan.closePopover('msg');
        this.msgOpenFlag = false;
    },
    /**
     * @param String url 浮动窗口url(默认加载当前页面的content)
     */
    openContent: function(url) {
        if (!url) throw new Error('url is null!');
        var titHeight = $('#header').offset().height;
        appcan.openPopoverByEle("content", url + ".html", 0, titHeight);
        window.onorientationchange = window.onresize = function() {
            appcan.frame.resize("content", 0, titHeight);
        }
    },
    zycon: function(url, top, id) {
        var bottom = $(".footerEvent").outerHeight();
        if (!bottom)
            bottom = 0;

        if (!id)
            id = "content";

        if (id == $(".footerEvent").attr("id") || $(".footerEvent").hasClass("hide"))
            bottom = 0;

        if (uexWidgetOne.platformName != "android" && url != "chat_detail_content" && url != "space_detail_content")
            bottom = 0;
        if (url.indexOf(".html") == -1)
            url += ".html";
        zy_con(id, url, 0, top, bottom);
    },
    /**
     * 关闭窗口
     * @param string n 关闭窗口动画，默认-1
     */
    close: function(n) {
        appcan.window.close(n || -1);
    }
}


/**
 * localStorage操作相关
 * @type {Object}
 */
var LS = {
    /**
     * [W(window简写) 窗口之间参数设置]
     * @type {Object}
     */
    W: {
        key: 'params',
        keys: null,
        initKeys: function () {
            if(!LS.W.keys){
                LS.W.keys = [];
                for(var _key in constant.PARAMS){
                    LS.W.keys.push(constant.PARAMS[_key]);
                }
            }
        },
        checkKey: function (key) {
            if(!~LS.W.keys.indexOf(key)) throw new Error('key was an unknown param!');
        },
        getParams: function () {
            return LS.get(LS.W.key) || {};
        },
        set: function (key, val) {
            LS.W.checkKey(key);
            var params = LS.W.getParams();
            params[key] = val;
            LS.set(LS.W.key, params);
        },
        get: function (key) {
            LS.W.checkKey(key);
            return LS.W.getParams()[key];
        },
        clear: function (key) {
            if(key){
                LS.W.checkKey(key);
                var params = LS.W.getParams();
                delete params[key];
                LS.set(LS.W.key, params);
            }else{
                LS.clear(LS.W.key, params);
            }
        }
    },
    V: {
        key: 'vars',
        keys: null,
        initKeys: function () {
            if(!LS.V.keys){
                LS.V.keys = [];
                for(var _key in constant.VAR){
                    LS.V.keys.push(constant.VAR[_key]);
                }
            }
        },
        checkKey: function (key) {
            if(!~LS.V.keys.indexOf(key)) throw new Error('key was an unknown param!');
        },
        getParams: function () {
            return LS.get(LS.V.key) || {};
        },
        set: function (key, val) {
            LS.V.checkKey(key);
            var params = LS.V.getParams();
            params[key] = val;
            LS.set(LS.V.key, params);
        },
        get: function (key) {
            LS.V.checkKey(key);
            return LS.V.getParams()[key];
        },
        clear: function (key) {
            if(key){
                LS.V.checkKey(key);
                var params = LS.V.getParams();
                delete params[key];
                LS.set(LS.V.key, params);
            }else{
                LS.clear(LS.V.key, params);
            }
        }
    },
    /**
     * localStorage保存数据
     * @param String key  保存数据的key值
     * @param String value  保存的数据
     */
    set: function(key, json) {
        window.localStorage.setItem(key, JSON.stringify(json));
    },
    /**
     * 根据key取localStorage的值
     * @param Stirng key 保存的key值
     */
    get: function(key) {
        var str = window.localStorage.getItem(key);
        if (str != null && str != "")
            return JSON.parse(str);
        else
            return false;
    },
    /**
     * 清除缓存
     * @param Striong key  保存数据的key，如果不传清空所有缓存数据
     */
    clear: function(key) {
        if (key)
            window.localStorage.removeItem(key);
        else {
            // var keys = appcan.locStorage.keys(),
            //     singleKey,
            //     i = 0;
            // while(singleKey = keys[i++]){
            //     appcan.locStorage.remove(singleKey);
            // }
            window.localStorage.clear();
        }
    }
}


/**
 * appcan插件相关的简化封装
 * @type {Object}
 */
appcan.extend({
    v: { // UI视图相关
        buttons: function(opts, ele) {
            if (Utils.type(opts) != 'object') throw new Error('opts should be an object!');
            appcan.button(ele || '._click_btn', 'ani-act', function() {
                for (var key in opts) {
                    if ((key + '') === this.id) {
                        opts[key] && opts[key].call(this);
                        break;
                    }
                }
            });
        }
    },
    c: { // 窗口通讯相关
        /**
         * [pop 在指定的弹出窗内执行相应的脚本]
         * @param {[string]} popName [弹出窗口名称]
         * @param {[string]} js      [要执行的js代码]
         */
        pop: function(popName, js, name) {
            appcan.window.evaluatePopoverScript({
                name: name || '',
                popName: popName,
                scriptContent: js
            });
        },
        /**
         * [main 在指定的窗口脚本执行]
         * @param {[type]} name [窗口名称]
         * @param {[type]} js   [js代码]
         */
        main: function(name, js) {
            appcan.window.evaluateScript({
                name: name,
                scriptContent: js
            });
        },
        /**
         * [sub 订阅一个频道，如果有消息发给该频道，则会执行响应的回调]
         * @param {[type]} channelID [频道名称]
         * @param {[type]} jsonObject     [绑定的执行的回调的json对象]
         */
        sub: function(channelID, jsonObject) {
            appcan.window.subscribe(channelID, function(receiveKey) {
                var callback;
                for (var key in jsonObject) {
                    if (key == receiveKey) {
                        callback = jsonObject[key];
                        if (callback && Utils.type(callback) == 'function') callback.call(this);
                        break;
                    }
                }
            });
        },
        /**
         * [SendNotification 向指定通道发送消息]
         * @param {[String]} channelID [频道名称]
         * @param {[String]} key      [发送的消息]
         */
        pub: function(channelID, key) {
            appcan.window.publish(channelID, key)
        }
    }
});


/**
 * 事件处理相关工具类
 * @param  {[type]} function( [description]
 * @return {[type]}           [description]
 */
var EventUtil = (function() {
    var _util = {
        delayMaxTime: 60 * 60 * 2 * 1000, // 2小时
        interval: 200, // 200毫秒
        deferInterval: 10 // defer间隔数,10毫秒
    }, _public = {
        isFunc: function(value){
            return Object.prototype.toString.call(value) === '[object Function]';
        },
        isArray: function(value){
            return Object.prototype.toString.call(value) === '[object Array]';
        },
        // 继承
        extend: function(){
            var i = 1,
                len = arguments.length,
                target = arguments[0],
                j;
            if (i == len) {
                target = this;
                i--;
            }
            for (; i < len; i++) {
                for (j in arguments[i]) {
                    target[j] = arguments[i][j];
                }
            }
            return target;
        }
    }, _event = {
        delay: 50,
        args: null,
        add: function() {
            if (!_event.args) {
                _event.args = Array.prototype.slice.call(arguments);
            }
            if (_event.args.length == 0) {
                _event.args = null;
                return false;
            }

            var arg = _event.args.shift(),
                isFunc = _public.isFunc(arg),
                isArray = _public.isArray(arg);

            if (isArray && arg.length != 2) {
                throw new Errr('arg length is not right');
            }
            setTimeout(function() {
                if (isFunc) {
                    arg.call(null);
                    _event.add(_event.args);
                } else if (isArray) {
                    arg[1] && _public.isFunc(arg[1]) && arg[1].call(null);
                    _event.add(_event.args);
                } else {
                    throw new Error('type is unknow');
                }
            }, isArray ? arg[0] : _event.delay);
        }
    };
    // test:
    // _event.add(function(){ console.log('hello') }, [500,function(){ console.log('world'); }]);

    // 绑定事件
    _util.bind = function(obj, type, handle) {
        if (document.addEventListener) { // Chrome、FireFox、Opera、Safari、IE9.0及其以上版本
            obj.addEventListener(type, handle, false);
        } else if (document.attachEvent) { // IE8.0及其以下版本
            obj.attachEvent('on' + type, handle);
        } else { // 早期浏览器
            obj['on' + type] = handle;
        }
    }

    // 节流器
    _util.throttleFire = function() {
        // 获取第一个参数
        var isClear = arguments[0],
            fn;
        if (typeof isClear == 'boolean') {
            fn = arguments[1];
            fn.__throttleID && clearTimeout(fn.__throttleID);
        } else {
            fn = isClear;
            param = arguments[1];
            var p = _public.extend({
                context: null,
                args: [],
                time: 300
            }, param);
            arguments.callee(true, fn);
            fn.__throttleID = setTimeout(function() {
                fn.apply(p.context, p.args);
            }, p.time);
        }
    }
    // 延迟顺序执行(for optimise)
    _util.deferFire = _event.add;
    _util.delayFire = function(name, condition, callback) {
        var count = 0,
            conditionType = Core.isType(condition, 'function');
        var timer = setInterval(function() {
            conditionFlag = conditionType ? condition.call(this) : condition;
            if (conditionFlag) {
                clearInterval(timer);
                callback && callback.call(this);
            } else {
                count += 100;
                if (count >= _util.delayMaxTime) {
                    clearInterval(timer);
                    if (window.console) window.console.log(name + 'timer failed');
                }
            }
        }, _util.interval);
    };
    // 阻止默认事件
    _util.stopDefault = function(e) {
        if (e.preventDefault) {
            e.preventDefault(); // 支持DOM的标准浏览器
        } else {
            e.returnValue = false; // IE
        }
        return false;
    };
    // 冒泡：父元素相关的事件的触发
    _util.stopBubble = function(e) {
        if (window.event) {
            e.cancelBubble = false; // ie下阻止冒泡
        } else {
            e.stopPropagation(); // 其他浏览器下阻止冒泡
        }
    }
    return {
        bind: _util.bind,
        throttleFire: _util.throttleFire,
        delayFire: _util.delayFire,
        deferFire: _util.deferFire,
        stopDefault: _util.stopDefault,
        stopBubble: _util.stopBubble
    }
}());



///////////////////////////////我是万恶的分割线/////////////////////////////
/**
 * [bind the _public object to the window]
 * @return {[type]} [description]
 */
(function(){

    tools.bindPublicToWindow();

    LS.W.initKeys();
    LS.V.initKeys();

    appcan && appcan.ready(function () {
        uexWidgetOne.cbError = function (opId, type, error) {
            debug && alert(JSON.stringify(error));
        }
    });
})();

var CurrentUser = LS.V.get(constant.VAR.USER_KEY);
if(!CurrentUser){
    LS.V.set(constant.VAR.USER_KEY, {
        username: '123456',
        password : '123456',
    });
}


